<template>
  <div class="book-management">
    <h1 class="title">图书管理系统</h1>
    
    <div class="operation-bar">
      <el-button type="primary" @click="showAddDialog">添加新图书</el-button>
      <el-input
        v-model="searchKeyword"
        placeholder="输入书名或作者搜索"
        style="width: 300px; margin-left: 20px;"
        clearable
        @clear="handleSearchClear"
        @keyup.enter.native="handleSearch"
      >
        <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
      </el-input>
    </div>
    
    <el-table 
      :data="paginatedBookList" 
      border 
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
      <el-table-column prop="title" label="书名"></el-table-column>
      <el-table-column prop="author" label="作者"></el-table-column>
      <el-table-column prop="copies" label="库存数量" width="120" align="center"></el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template v-slot="scope">
          <el-button
            size="mini"
            type="primary"
            @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="filteredBookList.length"
      style="margin-top: 20px; text-align: right;"
    >
    </el-pagination>

    <el-dialog 
      :title="dialogTitle" 
      :visible.sync="dialogVisible" 
      width="500px"
      @closed="handleDialogClosed"
    >
      <el-form 
        :model="currentBook" 
        :rules="rules" 
        ref="bookForm" 
        label-width="100px"
      >
        <el-form-item label="书名" prop="title">
          <el-input v-model="currentBook.title" placeholder="请输入书名"></el-input>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="currentBook.author" placeholder="请输入作者"></el-input>
        </el-form-item>
        <el-form-item label="库存数量" prop="copies">
          <el-input-number 
            v-model="currentBook.copies" 
            :min="1" 
            :max="100"
            controls-position="right"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'BookManagement',
  data() {
    return {
      bookList: [
        {"id": 1, "title": "Python编程", "author": "John Doe", "copies": 4},
        {"id": 2, "title": "历史的秘密", "author": "Jane Smith", "copies": 3},
        {"id": 3, "title": "宇宙探索", "author": "Emily Brown", "copies": 2},
        {"id": 4, "title": "健康生活", "author": "Mike Johnson", "copies": 5},
        {"id": 5, "title": "数学之美", "author": "Sarah Lee", "copies": 4},
        {"id": 6, "title": "艺术欣赏", "author": "David White", "copies": 3},
        {"id": 7, "title": "编程入门", "author": "Alice Green", "copies": 2},
        {"id": 8, "title": "科幻世界", "author": "Frank Black", "copies": 5},
        {"id": 9, "title": "自然奇观", "author": "Grace Blue", "copies": 4},
        {"id": 10, "title": "音乐之声", "author": "Tom Red", "copies": 3}
      ],
      filteredBookList: [],
      paginatedBookList: [],
      dialogVisible: false,
      currentBook: {
        id: null,
        title: '',
        author: '',
        copies: 1
      },
      isEditMode: false,
      rules: {
        title: [
          { required: true, message: '请输入书名', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
        ],
        author: [
          { required: true, message: '请输入作者', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur' }
        ]
      },
      searchKeyword: '',
      currentPage: 1,
      pageSize: 5,
      loading: false
    }
  },
  computed: {
    dialogTitle() {
      return this.isEditMode ? '编辑图书信息' : '添加新图书'
    }
  },
  created() {
    this.filteredBookList = [...this.bookList]
    this.paginateBooks()
  },
  methods: {
    showAddDialog() {
      this.isEditMode = false
      this.currentBook = { id: null, title: '', author: '', copies: 1 }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.bookForm && this.$refs.bookForm.clearValidate()
      })
    },
    
    handleEdit(row) {
      this.isEditMode = true
      this.currentBook = { ...row }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.bookForm && this.$refs.bookForm.clearValidate()
      })
    },
    
    confirmSubmit() {
      this.$refs.bookForm.validate((valid) => {
        if (valid) {
          if (this.isEditMode) {
            this.updateBook()
          } else {
            this.addBook()
          }
        }
      })
    },
    
    addBook() {
      const newId = this.bookList.length > 0 
        ? Math.max(...this.bookList.map(book => book.id)) + 1 
        : 1
      
      this.bookList.push({
        id: newId,
        title: this.currentBook.title,
        author: this.currentBook.author,
        copies: this.currentBook.copies
      })
      
      this.dialogVisible = false
      this.$message.success('图书添加成功！')
      this.handleSearch()
    },
    
    updateBook() {
      const index = this.bookList.findIndex(book => book.id === this.currentBook.id)
      if (index !== -1) {
        this.bookList.splice(index, 1, { ...this.currentBook })
        this.dialogVisible = false
        this.$message.success('图书信息更新成功！')
        this.handleSearch()
      }
    },
    
    handleDelete(row) {
      this.$confirm(`确定要删除《${row.title}》吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.bookList.findIndex(book => book.id === row.id)
        if (index !== -1) {
          this.bookList.splice(index, 1)
          this.$message.success('删除成功!')
          this.handleSearch()
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    
    handleSearch() {
      this.loading = true
      setTimeout(() => {
        if (this.searchKeyword.trim() === '') {
          this.filteredBookList = [...this.bookList]
        } else {
          const keyword = this.searchKeyword.toLowerCase()
          this.filteredBookList = this.bookList.filter(book => 
            book.title.toLowerCase().includes(keyword) || 
            book.author.toLowerCase().includes(keyword)
          )
        }
        this.currentPage = 1
        this.paginateBooks()
        this.loading = false
      }, 300)
    },
    
    handleSearchClear() {
      this.searchKeyword = ''
      this.handleSearch()
    },
    
    handleSizeChange(val) {
      this.pageSize = val
      this.paginateBooks()
    },
    
    handleCurrentChange(val) {
      this.currentPage = val
      this.paginateBooks()
    },
    
    paginateBooks() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      this.paginatedBookList = this.filteredBookList.slice(start, end)
    },
    
    handleDialogClosed() {
      this.$refs.bookForm.resetFields()
    }
  },
  watch: {
    searchKeyword() {
      if (this.searchKeyword === '') {
        this.handleSearch()
      }
    }
  }
}
</script>

<style scoped>
.book-management {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.title {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.el-table {
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>